package magic.deckbuilder;

import java.util.ArrayList;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

public class MagicDeckDB {

	private static final int VERSION_DB = 1;
	private static final String NOM_DB = "magicDeck.db";

	private SQLiteDatabase db;

	private MagicDeckDBStructure magicDeckDBStructure;

//	private CardDBController cardContoller;

//	private Context context;

	public MagicDeckDB(Context context) {
//		this.context = context;
		magicDeckDBStructure = new MagicDeckDBStructure(context, NOM_DB, null,
				VERSION_DB);
	}

	public void open() {
			db = magicDeckDBStructure.getWritableDatabase();
	}

	public void close() {
		db.close();
	}

	public SQLiteDatabase getDB() {
		return db;
	}

	public long insertCard(Card card) {
		return -1; // TODO :: instance of card controller
//		return cardContoller.insert(card);
	}

	public ArrayList<Deck> getDecks() {
		return getDecks(null);
	}

	public ArrayList<Deck> getDecks(String orderBy) {
		//db.query(MagicDeckDBStructure.TABLE_DECK, new String[] { Deck.TAG, Deck.RESUME }, null, null, null, null, orderBy);
		return MagicDeckDB.defaultDeck();
	}

	protected ArrayList<Deck> cursorToDecks(Cursor cursor) {
		cursor.moveToFirst();
		int column = cursor.getColumnCount();
		ArrayList<Deck> decks = new ArrayList<Deck>(cursor.getColumnCount());
		for (int i = 0; i < column; i++) {
			decks.add(new Deck(cursor.getString(1), cursor.getString(2)));
		}
		return decks;
	}

	public static ArrayList<Deck> defaultDeck() {
		ArrayList<Deck> decks = new ArrayList<Deck>();
		decks.add(new Deck("A", "deck 1"));
		decks.add(new Deck("B", "deck 2"));
		decks.add(new Deck("C", "deck 3"));
		decks.add(new Deck("D", "deck 4"));
		decks.add(new Deck("E", "deck 5"));
		decks.add(new Deck("F", "deck 6"));
		decks.add(new Deck("G", "deck 7"));
		decks.add(new Deck("H", "deck 8"));
		decks.add(new Deck("I", "deck 9"));
		decks.add(new Deck("J", "deck 10"));
		decks.add(new Deck("K", "deck 11"));
		return decks;

	}
	
	public long insertDeck(Deck deck) {
		ContentValues values = new ContentValues();
		values.put(MagicDeckDBStructure.COL_ISBN, deck.getTag());
		values.put(MagicDeckDBStructure.COL_TITRE, deck.getResume());
		return db.insert(MagicDeckDBStructure.TABLE_LIVRES, null, values);
	}

	public long createDeck(String tag, String resume)
			throws DeckBuilderException {
		if (db == null)
			open();
		if (tag.length() <= 0)
			throw new DeckBuilderException();
		ContentValues values = new ContentValues();
		values.put(Deck.TAG, tag);
		values.put(Deck.RESUME, resume);
		return db.insert(MagicDeckDBStructure.TABLE_DECK, null, values);
	}
}